<?php

namespace app\user\controller\group_activity\log;

use app\admin\service\UserService;
use app\BaseController;
use app\model\group_activity\GroupActivityTaskCommentModel;
use app\model\group_activity\GroupActivityTaskModel;
use app\model\group_activity\GroupActivityTaskUserModel;
use app\model\group_activity\GroupActivityTaskUserResultModel;
use think\App;

class Index extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 参与记录
     * @return bool|string
     */
    public function index(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'pageSize|每页显示数量' => 'require',
            ]);
            $where = [];
            $taskWhere = [];
            if (!empty($param['name'])) {
                $taskWhere[] = ['name', 'like', '%' . $param['name'] . '%'];
            }
            if (!empty($param['type_id'])){
                $taskWhere[] = ['type_id', '=', $param['type_id']];
            }
            if (!empty($param['uid'])){
                $taskWhere[] = ['uid', '=', $param['uid']];
            }
            if (!empty($param['task_status'])){
                $taskWhere[] = ['status', '=', $param['task_status']];
            }
            if (isset($param['is_task']) &&  strlen($param['is_task']) > 0) {
                $taskWhere[] = ['is_task', '=', $param['is_task']];
            }
            if (!empty($taskWhere)){
                $GroupActivityTaskModel = new GroupActivityTaskModel();
                $task_id = $GroupActivityTaskModel->where($taskWhere)->column('id');
                if (!empty($task_id)){
                    $where[] = ['id', 'in', $task_id];
                }else{
                    $where[] = ['id', '=', -1];
                }
            }
            if (isset($param['audit_status']) &&  strlen($param['audit_status']) > 0) {
                $where[] = ['audit_status', '=', $param['audit_status']];
            }
            if (isset($param['status']) && strlen($param['status']) > 0){
                $where[] = ['status', '=', $param['status']];
            }
            if (isset($param['is_comment']) && strlen($param['is_comment']) > 0){
                $where[] = ['is_comment', '=', $param['is_comment']];
            }
            $where[] = ['uid','=',$this->userData['id']];
            $GroupActivityTaskUserModel = new GroupActivityTaskUserModel();
            $data = $GroupActivityTaskUserModel->where($where)->with([
                'task' => function ($query) {
                    $query->with([
                        'user' => function ($query) {
                            $query->with(['roleName']);
                        },
                        'typeName'
                    ]);
                }
            ])->order('id','desc')->paginate($param['pageSize'])->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 删除记录
     * @return bool|string
     */
    public function del(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
            ]);
            $GroupActivityTaskUserModel = new GroupActivityTaskUserModel();
            $GroupActivityTaskUserModel->where('id', 'in', $param['id'])->update([
                'is_del' => 1,
                'del_time' => time()
            ]);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 详情
     * @return bool|string
     */
    public function info(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require|number',
            ]);
            $GroupActivityTaskUserModel = new GroupActivityTaskUserModel();
            $info = $GroupActivityTaskUserModel->with([
                'task' => function ($query) {
                    $query->with([
                        'user' => function ($query) {
                            $query->with(['roleName']);
                        },
                        'typeName',
                        'taskRatingScale' => function ($query) {
                            $query->with(['RatingScale']);
                        },
                        'taskDepartment',
                    ]);
                }
            ])->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $info = $info->toArray();
            if ($info['task_is_task'] == 1){
                $GroupActivityTaskUserResultModel = new GroupActivityTaskUserResultModel();
                foreach ($info['taskRatingScale'] as &$value) {
                    $result = $GroupActivityTaskUserResultModel->field('id,callable_view')->where([
                        ['task_user_id', '=', $param['id']],
                        ['rating_scale_id','=',$value['rating_scale_id']]
                    ])->find();
                    if ($result){
                        $value['result_id'] = $result['id'];
                        $value['callable_view'] = $result['callable_view'];
                    }else{
                        $value['result_id'] = 0;
                        $value['callable_view'] = 0;
                    }
                }
            }
            if (!empty($info['taskDepartment'])){
                $UserService = new UserService($this->app);
                $DepartmentData = $UserService->getNotDelDepartmentAffiliationAll($this->userData['unit_id']);
                foreach ($info['taskDepartment'] as &$value) {
                    $value['department_name'] = $DepartmentData[$value['department_id']]['all_name']??'--';
                }
            }
            $info['task_user_role'] = $info['task_user_role']??'超级管理员';
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 签到
     * @return bool|string
     */
    public function sign(): bool|string
    {
        $GroupActivityTaskUserModel = new GroupActivityTaskUserModel();
        $GroupActivityTaskUserModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require|number',
            ]);
            $info = $GroupActivityTaskUserModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            if ($info['is_sign'] == 1) throw new \Exception('不可重复签到！');
            $info->save([
                'is_sign' => 1,
                'status' => 3,
                'sign_time' => time()
            ]);
            $GroupActivityTaskModel = new GroupActivityTaskModel();
            $taskInfo = $GroupActivityTaskModel->find($info['task_id']);
            $taskInfo->inc('sign_num')->save();
            $GroupActivityTaskUserModel->commit();
            return success();
        } catch (\Exception $e) {
            $GroupActivityTaskUserModel->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 请假
     * @return bool|string
     */
    public function askForLeave(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
                'leave_reason|请假原因' => 'require'
            ]);
            $GroupActivityTaskUserModel = new GroupActivityTaskUserModel();
            $info = $GroupActivityTaskUserModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            if ($info['leave_status'] == 1) throw new \Exception('请假正在审核中！');
            if ($info['leave_status'] == 2) throw new \Exception('不可重复请假！');
            $info->save([
                'leave_status' => 1,
                'leave_reason' => $param['leave_reason']
            ]);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 评论
     * @return bool|string
     */
    public function comment(): bool|string
    {
        $GroupActivityTaskUserModel = new GroupActivityTaskUserModel();
        $GroupActivityTaskUserModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
                'content|评论内容' => 'require'
            ]);
            $info = $GroupActivityTaskUserModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            if ($info['is_comment'] == 1) throw new \Exception('只能评论一次');
            $GroupActivityTaskCommentModel = new GroupActivityTaskCommentModel();
            $GroupActivityTaskCommentModel->insert([
                'task_id' => $info['task_id'],
                'uid' => $this->userData['id'],
                'content' => $param['content'],
                'time' => time()
            ]);
            $info->save([
                'is_comment' => 1
            ]);
            $GroupActivityTaskUserModel->commit();
            return success();
        } catch (\Exception $e) {
            $GroupActivityTaskUserModel->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }
}